package cn.school.iot.service.impl;

import cn.school.common.api.CommonPage;
import cn.school.common.api.CommonResult;
import cn.school.common.utils.SysUserUtils;
import cn.school.iot.dao.IotDeviceOperateLogDao;
import cn.school.iot.eneity.IotDeviceOperateLogInfo;
import cn.school.iot.param.LogParam;
import cn.school.iot.service.IotDeviceOperateLogService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Description: 门禁规则操作日志Service
 * @ClassName: IotDeviceOperateLogServiceImpl
 * @Author: tzw
 * @Date: 2024/4/22 8:05
 */
@Service
public class IotDeviceOperateLogServiceImpl extends ServiceImpl<IotDeviceOperateLogDao,IotDeviceOperateLogInfo> implements IotDeviceOperateLogService {
    @Override
    public CommonResult addLog(IotDeviceOperateLogInfo info) {
        info.setCreateTime(new Date());
        int result = this.baseMapper.insert(info);
        if (result > 0){
            return CommonResult.success();
        }
        return CommonResult.failed();
    }

    @Override
    public CommonResult<CommonPage> selectIotDeviceOperateLogList(LogParam logParam) {
        LambdaQueryWrapper<IotDeviceOperateLogInfo> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(logParam.getDeviceType())){
            queryWrapper.eq(IotDeviceOperateLogInfo::getDeviceType,logParam.getDeviceType());
        }
        if (StringUtils.isNotBlank(logParam.getResult())){
            queryWrapper.eq(IotDeviceOperateLogInfo::getResult,logParam.getResult());
        }
        if (StringUtils.isNotBlank(SysUserUtils.getSysUser().getTenantId())){
            queryWrapper.eq(IotDeviceOperateLogInfo::getTenantId, SysUserUtils.getSysUser().getTenantId());
        }
        IPage<IotDeviceOperateLogInfo> page = new Page<>(logParam.getPageNum(),logParam.getPageSize());
        IPage<IotDeviceOperateLogInfo> deviceOperateLogInfoIPage = this.baseMapper.selectPage(page, queryWrapper);
        CommonPage commonPage = new CommonPage();
        commonPage.setPageSize(logParam.getPageSize());
        commonPage.setPageNum(logParam.getPageNum());
        commonPage.setTotalPage((int) deviceOperateLogInfoIPage.getPages());
        commonPage.setList(deviceOperateLogInfoIPage.getRecords());
        commonPage.setTotal(deviceOperateLogInfoIPage.getTotal());
        return CommonResult.success(commonPage);
    }
}
